package com.wx.house.manager.api.fileupload.controller;

import com.wx.house.common.base.ProjectConfiguration;
import com.wx.house.common.util.IDUtils;
import com.wx.house.common.util.MapUtil;
import com.wx.house.core.pojo.dto.fileload.AttaUploadDto;
import com.wx.house.manager.api.capital.text.IDinformation;
import com.wx.house.manager.api.fileupload.service.FileUploadService;
import com.wx.house.common.assembly.alyidcard.IDCardUtil;
import com.wx.house.common.assembly.alyidcard.IDocrResult;
import com.wx.house.common.base.BaseController;
import com.wx.house.common.exception.BusinessException;
import com.wx.house.core.pojo.base.Result;
import com.wx.house.core.pojo.po.fileupload.AttaUpload;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;


/**
 * @Title:
 * @BelongProjecet com-wx-house
 * @BelongPackage com.wx.house.api.fileupload.controller
 * @Description:
 * @Author: yxc
 * @Date: 2019/11/11 9:25
 * @Version V1.0
 */
@RestController
@RequestMapping("file/")
@Api(value = "附件上传", tags = "附件上传")
@Slf4j
public class FileUploadController extends BaseController {
private static final String CODE = "ALY:ID_CODE:%s";
@Resource
private FileUploadService fileUploadService;
@Resource
private final ResourceLoader resourceLoader;
@Resource
private ProjectConfiguration projectConfiguration;
@Resource
private IDCardUtil iDCardUtil;

@Autowired
public FileUploadController(ResourceLoader resourceLoader) {
	this.resourceLoader = resourceLoader;
}

@PostMapping("add/")
@ApiOperation(value = "上传附件", notes = "模块：上传附件")
@ApiImplicitParams({
		@ApiImplicitParam(name = "type", value = "附件类型（1 身份证正面 2身份证反面  3 合同 4 网站logo）", required = false, dataType = "String", paramType = "query")
})
public Result addFlowmeter(@ApiParam(value = "文件") @RequestParam(value = "file", required = true)
		                           MultipartFile file, HttpServletRequest request, @RequestParam(defaultValue = "1") String type, String id) {

	if (StringUtils.isEmpty(id)) {
	    //生成一个文件id
	   id= IDUtils.genItemId(12)+"";
	}
	AttaUpload upload = fileUploadService.multiUploads(file, type, id);
	//获取文件预览路径
	upload.setUrl(projectConfiguration.getStaticResource().getStaticResourceUrl() + upload.getUrl());
	return Result.success(upload);
}


@PostMapping("upload/")
@ApiOperation(value = "上传附件(手机文件上传)", notes = "模块：上传附件(手机文件上传)")
public Result addFlowmeter(@RequestBody AttaUploadDto attaUploadDto) throws IOException {
	AttaUpload upload =null;
	String encodedImageStr = attaUploadDto.getEncodedImageStr();
	byte[] decode = Base64.getDecoder().decode(encodedImageStr);
	ByteArrayInputStream in = new ByteArrayInputStream(decode);  
	 BufferedImage bim = ImageIO.read(in);
	 Integer desMaxWidth=856;
     Integer desMaxHeight=540;
     int srcWidth = bim.getWidth();
     int srcHeight = bim.getHeight();
     Thumbnails.Builder builder = Thumbnails.of(bim).outputFormat("jpeg");
     // 指定大小（宽或高超出会才会被缩放）
     if (srcWidth > desMaxWidth || srcHeight > desMaxHeight) {
         builder.size(desMaxWidth, desMaxHeight);
     } else {
         //宽高均小，指定原大小
         builder.size(srcWidth, srcHeight);
     }
     // 写入到内存
     ByteArrayOutputStream baos = new ByteArrayOutputStream(); //字节输出流（写入到内存）
     builder.toOutputStream(baos);
     IDocrResult iDocrResult = iDCardUtil.OcrValidated(baos.toByteArray());
	if("1".equals(iDocrResult.getCode())) {
    	IDinformation iDinformation=MapUtil.mapToPojo((HashMap<String, String>)iDocrResult.getResult(), IDinformation.class);
    	BeanUtils.copyProperties(iDinformation, iDocrResult.getResult());
    	if(!iDinformation.getName().equals(attaUploadDto.getOcrName())) {
    		 return Result.error("姓名与身份证姓名不匹配");
    	}
    	if(!iDinformation.getCode().equals(attaUploadDto.getOcrCode())) {
    		 return Result.error("身份证号与图片身份证号不匹配");
    	} 
    	redisUtil().set(String.format(CODE,iDinformation.getCode()), iDinformation.getName(), 3L, TimeUnit.HOURS);
    	upload = fileUploadService.upload(attaUploadDto);	//获取文件预览路径
		upload.setUrl(projectConfiguration.getStaticResource().getStaticResourceUrl() + upload.getUrl());
    	return Result.success(upload);
    }
    if("2".equals(iDocrResult.getCode())) {
    	upload = fileUploadService.upload(attaUploadDto);	//获取文件预览路径
		upload.setUrl(projectConfiguration.getStaticResource().getStaticResourceUrl() + upload.getUrl());
    	return Result.success(upload);
    }
    if("-1".equals(iDocrResult.getCode())) {
    	 return Result.error("图像为空");
	}
	if("-2".equals(iDocrResult.getCode())) {
		 return Result.error("图像格式错误");
	}
	if("-3".equals(iDocrResult.getCode())) {
		 return Result.error("图像无法加载");
	}
	if("-4".equals(iDocrResult.getCode())) {
		 return Result.error("图像无法识别");
	}
	if("-7".equals(iDocrResult.getCode())) {
		 return Result.error("身份证图片不完整");
	}
	if("-8".equals(iDocrResult.getCode())) {
		 return Result.error("图片请对应相应的格式");
	}
	if("-9".equals(iDocrResult.getCode())) {
		 return Result.error("没有信息");
	}
    else {
    	 return Result.error("身份证上传失败");
	}
}


@GetMapping("download/")
@ApiOperation(value = "下载附件", notes = "模块：下载附件")
public Result addFlowmeter(String imageName, HttpServletRequest request, HttpServletResponse response) {
	fileUploadService.getImg(imageName, response);
	return Result.success();
}

@DeleteMapping("deleteFile/{id}")
@ApiOperation(value = "删除附件", notes = "删除附件")
public Result deleteFlowmeter(@PathVariable String id) {
	//根据id查询附件
	AttaUpload upload = fileUploadService.getById(id);
	try {
		//本地删除文件
		FileUtils.forceDelete(new File(upload.getPath()));
	} catch (IOException e) {
		e.printStackTrace();
		throw new BusinessException("文件被占用，无法删除");
	}
	//数据库删除文件
	fileUploadService.removeById(id);
	return Result.success("成功删除");
}
}